package com.yuanda.erp9.syn.service.erp9.impl;

import com.alibaba.fastjson.JSONObject;
import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.contant.TableConstant;
import com.yuanda.erp9.syn.entity.*;
import com.yuanda.erp9.syn.enums.*;
import com.yuanda.erp9.syn.mapper.erp9.CmsSuppliersTempMapper;
import com.yuanda.erp9.syn.service.erp9.CmsBrandsTempService;
import com.yuanda.erp9.syn.service.erp9.CmsTopicUpdateSumLogService;
import com.yuanda.erp9.syn.util.CacheUtil;
import com.yuanda.erp9.syn.util.PriceUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.Strings;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @desc   csv数据组装的实现类
 * @author linuo
 * @time   2022年12月1日10:03:07
 */
@Slf4j
public class CsvSaveImpl {
    @Resource
    protected CmsBrandsTempService cmsBrandsTempService;

    @Resource
    protected CmsTopicUpdateSumLogService cmsTopicUpdateSumLogService;

    @Resource
    protected CmsSuppliersTempMapper cmsSuppliersTempMapper;

    protected static CacheUtil.Cache brandCache = CacheUtil.init(CachePrefixEnum.BRAND.getKey());
    protected static CacheUtil.Cache suppliersCache = CacheUtil.init(CachePrefixEnum.SUPPLIERS.getKey());
    protected static CacheUtil.ObjectCache exchangeRates = CacheUtil.objectInit(CachePrefixEnum.EXCHANGE_RATES.getKey());

    /**
     * 计算商品单价
     * @param list 阶梯价格信息
     * @return 返回计算结果
     */
    protected Double calculateUnitPrice(List<CmsPricesEntity> list) {
        double result = 0D;
        // 计算单价
        if (list.size() > 0) {
            CmsPricesEntity cmsPricesEntity = list.get(0);

            BigDecimal price = cmsPricesEntity.getPrice();

            // 判断币种如果是美元，需要乘以汇率计算出人民币价格再计算单价
            Integer currency = cmsPricesEntity.getCurrency();
            if(currency.intValue() == CurrencyEnum.DOLLAR.getCode().intValue()){
                BigDecimal effectiveData = (BigDecimal) exchangeRates.get(CachePrefixEnum.EXCHANGE_RATES.getKey());
                if (effectiveData != null) {
                    price = effectiveData.multiply(price);
                }
            }

            Long min = cmsPricesEntity.getMin();
            if (price != null && min != null && min != 0) {
                BigDecimal divide = price.divide(BigDecimal.valueOf(min), 4, RoundingMode.HALF_UP);
                result = divide.doubleValue();
            }
        }
        return result;
    }

    /**
     * 格式化时间为yyyy-mm-dd HH:mm:ss格式
     * @param date 时间
     * @return 返回格式化后的时间
     */
    protected String dateFormat(Date date){
        if(date == null){
            return null;
        }
        return new SimpleDateFormat("yyyy-mm-dd HH:mm:ss").format(date);
    }

    /**
     * 处理阶梯价格，前面有美元标记的去除
     * @param priceBreak 阶梯价格
     * @return 返回处理完的阶梯价格
     */
    protected String handlePriceBreak(String priceBreak){
        if(priceBreak.startsWith("$")){
            priceBreak = priceBreak.substring(1);
        }
        return priceBreak;
    }

    /**
     * 插入品牌数据
     * @param name 品牌名称
     */
    protected Integer insertBrand(String name){
        CmsBrandsTempEntity entity = new CmsBrandsTempEntity();
        entity.setName(name);
        entity.setTag(BrandTagEnum.NEW.getCode());

        // 添加数据
        cmsBrandsTempService.insert(entity);

        // 缓存
        CacheUtil.Cache cache = CacheUtil.init(TableConstant.CMS_BRANDS_TEMP);
        cache.put(entity.getName(), entity.getBrandid());

        return entity.getBrandid();
    }

    /**
     * 组装阶梯价格数据
     * @param goodId 商品id
     * @param min 最小值
     * @param max 最大值
     * @param price 进价
     * @param currency 货币1人民币2美元
     * @param position 位置
     */
    protected CmsPricesEntity createCmsPriceData(String goodId, Long min, Long max, String price, Integer currency, Integer position){
        CmsPricesEntity cmsPricesEntity = new CmsPricesEntity();
        cmsPricesEntity.setGoodid(goodId);
        cmsPricesEntity.setLadderid(0);
        cmsPricesEntity.setMin(min);
        cmsPricesEntity.setMax(max == null ? 0 : max);

        BigDecimal goodsPrice;
        if(!Strings.isEmpty(price)){
            price = handlePriceBreak(price);

            // 处理阶梯价格中的单价，小数位小于4位的用0补齐，超过4位的保留原始数据
            goodsPrice = PriceUtil.handlePrice(price);
        }else{
            goodsPrice = BigDecimal.ZERO.setScale(4, BigDecimal.ROUND_UP);
        }

        cmsPricesEntity.setPrice(goodsPrice);

        cmsPricesEntity.setCurrency(currency);
        cmsPricesEntity.setDiscountRate(BigDecimal.valueOf(0.00));
        cmsPricesEntity.setPosition(position);
        cmsPricesEntity.setPublish(1);
        cmsPricesEntity.setCreatedAt(new Date(System.currentTimeMillis()));
        return cmsPricesEntity;
    }

    /**
     * 组装商品表-副表信息
     */
    protected CmsGoodsInformationEntity createCmsGoodsInformation(String goodId, Double inspectionChargesFee) {
        CmsGoodsInformationEntity cmsGoodsInformationEntity = new CmsGoodsInformationEntity();
        cmsGoodsInformationEntity.setActivity(0);
        cmsGoodsInformationEntity.setGoodid(goodId);
        cmsGoodsInformationEntity.setAtlas("");
        cmsGoodsInformationEntity.setEcnn(0);
        cmsGoodsInformationEntity.setTariffs(1);
        if(inspectionChargesFee != null && inspectionChargesFee > 0){
            cmsGoodsInformationEntity.setInspectionCharges(0);
        }else{
            cmsGoodsInformationEntity.setInspectionCharges(1);
        }
        cmsGoodsInformationEntity.setInspectionChargesFee(inspectionChargesFee);
        cmsGoodsInformationEntity.setCreatedAt(new Date(System.currentTimeMillis()));
        return cmsGoodsInformationEntity;
    }

    /**
     * 根据阶梯价格获取最小起订量
     * @param moqValue 最小起订量
     * @param list 阶梯价格数据
     * @return 返回结果
     */
    protected Long getMoqByLadderPriceList(Long moqValue, List<CmsPricesEntity> list){
        if(list != null && list.size() > 0){
            CmsPricesEntity cmsPricesEntity = list.get(0);
            Long min = cmsPricesEntity.getMin();
            if((moqValue == null) || (min != null && min > moqValue)){
                return Long.valueOf(min);
            }
        }
        return moqValue;
    }

    /**
     * 从费率的json中获取信息补充到商品表实体中
     * @param cmsGoodsEntity 商品表实体
     * @param json 费率的json
     * @return 返回处理后的商品表实体
     */
    protected CmsGoodsEntity addRateInfo(CmsGoodsEntity cmsGoodsEntity, JSONObject json){
        if(!json.isEmpty()){
            // 费率信息
            JSONObject rate = (JSONObject) json.get(RateCalculateConstants.RATE);
            cmsGoodsEntity.setRates(rate);

            // 关税率
            String tariffsRate = rate.getString(RateCalculateConstants.TARIFFRATE_FIELD);
            cmsGoodsEntity.setTariffsRate(Double.valueOf(tariffsRate));

            // 商检费
            String ciqPrice = rate.getString(RateCalculateConstants.CIQPRICE_FIELD);
            cmsGoodsEntity.setInspectionChargesFee(Double.valueOf(ciqPrice));

            // 是否需要3c认证
            String ccc = (String) json.get(RateCalculateConstants.CCC_FIELD);
            cmsGoodsEntity.setCcc(Integer.valueOf(ccc));

            // 是否禁运
            String embargo = (String) json.get(RateCalculateConstants.EMBARGO_FIELD);
            cmsGoodsEntity.setEmbargo(Integer.valueOf(embargo));

            // 是否禁运
            String eccn = (String) json.get(RateCalculateConstants.ECCN_FIELD);
            cmsGoodsEntity.setEccnNo(eccn);
        }
        return cmsGoodsEntity;
    }
}